package com.learning.demos.jvmgc;

import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;

/**
 * @author adolphw
 *
 * 我要被回收前需要被引用队列保存下
 */
public class ReferenceQueueDemo {

    public static void main(String[] args) throws InterruptedException {

        Object o1 = new Object();
        ReferenceQueue<Object> weakReferenceQueue = new ReferenceQueue<>();
        WeakReference<Object> weakReference = new WeakReference<>(o1, weakReferenceQueue);

        System.out.println(o1);
        System.out.println(weakReference.get());
        System.out.println(weakReferenceQueue.poll());

        System.out.println("_====================");
        o1 = null;
        System.gc();
        Thread.sleep(300);

        System.out.println(o1);
        System.out.println(weakReference.get());
        System.out.println(weakReferenceQueue.poll());
    }
}
